package org.gruposp2p.proyectokarma.service

import org.gruposp2p.proyectokarma.domain.Document;
import org.gruposp2p.proyectokarma.domain.DocumentTag;
import org.gruposp2p.proyectokarma.domain.Tag;
import org.codehaus.groovy.grails.commons.ConfigurationHolder
import org.codehaus.groovy.grails.web.json.JSONArray

class TagService {
	
	static transactional = true

	def updateDocumentTags(Document document, JSONArray tags) {
		tags.collect { collectedTag ->
			collectedTag = collectedTag.toLowerCase()
			def tag = Tag.findByName(collectedTag)
			def documentTag
			if (tag) {
				documentTag = DocumentTag.findWhere(document:document, tag:tag)
				if (!documentTag) {
					tag.frequency +=1
					tag.save()
					documentTag = new DocumentTag(document:document, tag:tag)
					documentTag.save()
				}
			} else {
				tag = new Tag(name:collectedTag, frequency:1)
				tag.save()
				documentTag = new DocumentTag(document:document, tag:tag)
				documentTag.save()
			}
		}
	}

	
}

